using AutoBackupSql.Jobs;
using AutoBackupSql.Models;
using AutoBackupSql.Services;
using Microsoft.Extensions.Options;
using Quartz;

namespace AutoBackupSql
{
    public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;
        private readonly ISchedulerFactory _schedulerFactory;
        private readonly BackupSettings _settings;

        public Worker(
            ILogger<Worker> logger,
            ISchedulerFactory schedulerFactory,
            IOptions<BackupSettings> settings)
        {
            _logger = logger;
            _schedulerFactory = schedulerFactory;
            _settings = settings.Value;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                _logger.LogInformation("MySQL自动备份服务启动中...");

                // 创建并配置调度器
                var scheduler = await _schedulerFactory.GetScheduler(stoppingToken);

                // 定义备份任务
                var jobKey = new JobKey("BackupJob", "BackupGroup");
                var job = JobBuilder.Create<BackupJob>()
                    .WithIdentity(jobKey)
                    .Build();

                // 定义触发器
                var triggerKey = new TriggerKey("BackupTrigger", "BackupGroup");
                var trigger = TriggerBuilder.Create()
                    .WithIdentity(triggerKey)
                    .WithCronSchedule(_settings.BackupSchedule.CronExpression)
                    .Build();

                // 调度任务
                await scheduler.ScheduleJob(job, trigger, stoppingToken);

                _logger.LogInformation("备份任务已调度，Cron表达式: {CronExpression}", _settings.BackupSchedule.CronExpression);

                // 启动调度器
                await scheduler.Start(stoppingToken);

                // 立即执行一次备份任务
                await scheduler.TriggerJob(jobKey, stoppingToken);

                _logger.LogInformation("MySQL自动备份服务已启动，等待执行备份任务...");

                // 保持服务运行
                while (!stoppingToken.IsCancellationRequested)
                {
                    await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
                }

                // 停止调度器
                await scheduler.Shutdown(stoppingToken);
                _logger.LogInformation("MySQL自动备份服务已停止");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "MySQL自动备份服务运行出错");
                throw;
            }
        }
    }
}
